/* Include files. */
#include "standard.h"

/* Macro constant definitions. */
#define LOCK_FILE_FMT 	"/var/run/%s.pid"
#define LOCK_MODE 		(S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)

/* Local function declarations. */

/* Macro API definitions. */

/* Global variable declarations. */

/* Type definitions. */

/* Local function definitions. */

static int getLockFile(const char *program, char *buf, int buf_len)
{
	const char *p = program, *q = p;

	while (NULL != (p = strchr(p, '/'))) {
		q = ++p;
	}

	return snprintf(buf, buf_len, LOCK_FILE_FMT, q);
}

static int lockFile(int fd)
{

	struct flock fl;

	fl.l_type = F_WRLCK;
	fl.l_start = 0;
	fl.l_whence = SEEK_SET;
	fl.l_len = 0;

	return (fcntl(fd, F_SETLK, &fl));

}

int alreadyRunning(const char *program)
{

	int fd;
	char buf[16];
	char locker[256] = {0};

	getLockFile(program, locker, sizeof(locker));
	fd = open(locker, O_RDWR | O_CREAT, LOCK_MODE);

	if (fd < 0) {
		perror("open()");
		exit(1);
	}

	if (lockFile(fd) < 0) {
		if (errno == EACCES || errno == EAGAIN) {
			close(fd);
			return (1);
		}

		perror("lockfile()");
		exit(1);
	}

	ftruncate(fd, 0);
	sprintf(buf, "%ld", (long)getpid());
	write(fd, buf, strlen(buf) + 1);
	//close(fd);

	return (0);
}

